package com.lfs.Servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.lfs.Dao.ProductDao;
import com.lfs.Entity.ProductEntity;
import com.lfs.Utils.PageModel;

@WebServlet("/ProductServlet")
public class ProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
			     String status = request.getParameter("status");
			     if (status.equals("ProductSelectAll")) {
			    	 ProductSelectAll(request,response);
				}else if (status.equals("ProductAdd")) {
					ProductAdd(request,response);
				}else if (status.equals("ProductDelect")) {
					ProductDelect(request,response);
				}else if (status.equals("ProductSelect")) {
					ProductSelect(request,response);
				}else if (status.equals("ProductUpate")) {
					ProductUpate(request,response);
				}else if (status.equals("PImgDown")) {
					PImgDown(request,response);
			    }else if (status.equals("Pvaild")) {
			    	Pvaild(request,response);
			}
	}

	private void Pvaild(HttpServletRequest request, HttpServletResponse response) throws IOException {
		   String name = request.getParameter("name");
		   boolean boo = ProductDao.Pvaild(name);
		   response.setCharacterEncoding("utf-8");
		   PrintWriter out = response.getWriter();
		   if (boo) {
			   out.print("����");
		   }else {
			   out.print("������");
		   }
		   out.close();
	}

	private void PImgDown(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		      String img = request.getParameter("img");
		      String newImg = new String(img.getBytes("iso-8859-1"),"utf-8");
		      String parent = getServletContext().getRealPath("/upload");
		      response.setContentType(getServletContext().getMimeType(newImg));
		      response.setHeader("Content-Disposition", "attachment;filename="+newImg);
		      File f = new File(parent,newImg);
			  InputStream is = new FileInputStream(f);
			  OutputStream os = response.getOutputStream();
		      byte[] b = new byte[1024];
		      while (true) {
		      int length = is.read(b, 0, b.length);
		      if (length != -1){
				  os.write(b, 0, length);
			  }else {
				  break;
		 }
	     }
		       is.close();
		       os.close();
		      
	}

	private void ProductUpate(HttpServletRequest request, HttpServletResponse response) throws IOException {
			  ProductEntity pe = FileUploadProduct(request);
			  boolean boo = ProductDao.ProductUpate(pe);
			  if (boo) {
				response.sendRedirect("ProductServlet?status=ProductSelectAll");
			}
	}

	@SuppressWarnings("deprecation")
	private void ProductDelect(HttpServletRequest request, HttpServletResponse response) throws IOException {
				String idStr = request.getParameter("id");
				int id = 0;
				if (idStr !=null) {
					id = new Integer(idStr);
				}
				boolean productDelect = ProductDao.ProductDelect(id);
				if(productDelect == false) {
					response.sendRedirect("ProductServlet?status=ProductSelectAll");
				}else {
					response.sendRedirect("ProductServlet?status=ProductSelectAll");
				}
	}

	@SuppressWarnings("deprecation")
	private void ProductSelect(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
				String idStr = request.getParameter("id");
				int id = 0;
				if (idStr !=null) {
					id = new Integer(idStr);
				}
			    ProductEntity pe = ProductDao.ProductSelect(id);
			    if (pe == null) {
			    	response.sendRedirect("ProductServlet?status=ProductSelectAll");
				}else {
					request.setAttribute("pe", pe);
					request.getRequestDispatcher("ProductUpdate.jsp").forward(request, response);
				}
	}

	private void ProductAdd(HttpServletRequest request, HttpServletResponse response) throws IOException {
				  ProductEntity pe = FileUploadProduct(request);
				  boolean boo = ProductDao.ProductAdd(pe);
				  if (boo) {
					response.sendRedirect("ProductServlet?status=ProductSelectAll");
				}
	}

	@SuppressWarnings({ "static-access", "deprecation" })
	private ProductEntity FileUploadProduct(HttpServletRequest request) {
				String idStr = request.getParameter("id");
				int id = 0;
				if (idStr != null) {
					id = new Integer(idStr);
				}
				String pname="",pdescribe="",pimg="";
				Double pprice = 0.00;
				int pnumber=0;
				String fileupload = getServletContext().getRealPath("/upload");
				File file = new File(fileupload);
				if (!file.exists()) {
					file.mkdirs();
				}
				int size = 1024*1024*2;
				FileItemFactory factory =  new DiskFileItemFactory(size, file);
				ServletFileUpload fileUpload = new ServletFileUpload(factory  );
				
				if (fileUpload.isMultipartContent(request)) {
					try {
						List<FileItem> list = fileUpload.parseRequest(request);
						for (FileItem fileItem : list) {
							if (fileItem.isFormField()) {
								String name = fileItem.getFieldName();
								if ("name".equals(name)) {
									pname = fileItem.getString("UTF-8");
								}else if ("describe".equals(name)) {
									pdescribe = fileItem.getString("UTF-8");
								}else if ("number".equals(name)) {
									pnumber = Integer.parseInt(fileItem.getString("UTF-8"));
								}else if ("price".equals(name)) {
									pprice = new Double(fileItem.getString("UTF-8"));
								}else if ("img".equals(name)) {
									pimg = fileItem.getString("UTF-8");
								}
						}else {
							 String uuidName = UUID.randomUUID().toString();
							 String name = uuidName+"-"+fileItem.getName();
							 File imageFile = new File(fileupload,name);
							 fileItem.write(imageFile);
							 pimg = name;
						}
							
					}
					} catch (FileUploadException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				ProductEntity pe = new ProductEntity(id,pname,pdescribe,pnumber,pprice,pimg);
				return pe;
	}

	@SuppressWarnings({ "deprecation" })
	private void ProductSelectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 		  String currentPagestr = request.getParameter("currentPage");
		          int currentPage = 1;
				  if (currentPagestr != null) {
					currentPage = new Integer(currentPagestr);
				}
				 int pageCount = 4;
				 int totleNum = ProductDao.ProductNum();
		         List<ProductEntity> productlist = ProductDao.ProductSelectAll(currentPage,pageCount);
		         PageModel<ProductEntity> page = new PageModel<>(pageCount, totleNum, currentPage, productlist);
		         request.setAttribute("page", page);
				 request.getRequestDispatcher("Productlist.jsp").forward(request, response);
	}

}
